<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script async src="//cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  <link href="//cdn.jsdelivr.net/npm/pace-js@1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />


















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />


<link href="https://fonts.loli.net/css?family=EB+Garamond:400,400i,700,700i|Noto+Serif+SC:400,500,700&display=swap&subset=chinese-simplified" rel="stylesheet">




  

<link href="//cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,Performance," />





  <link rel="alternate" href="/blog/atom.xml" title="叶金诚的站点" type="application/atom+xml" />






<meta name="description" content="摘自本人16年的的博客《Google官方  详解  Android 性能优化【史诗巨著之内存篇】》 博客使用的图片链接服务已经挂掉了，等以后有时间补上。 为什么关注性能# 对于一款APP，用户首先关注的是 app的性能，而不是APP本身的属性功能，用户不关心你是否是搞社交，是否搞电商，是否是一款强大的美图滤镜app，用户首先关注的是 性能—-性能不好，用户会直接卸载，在应用市场给一个恶狠狠得差评，">
<meta property="og:type" content="article">
<meta property="og:title" content="Android性能优化【史诗巨著之内存篇】">
<meta property="og:url" content="http://idolcoder.gitee.io/blog/2016/06/performance-android/index.html">
<meta property="og:site_name" content="叶金诚的站点">
<meta property="og:description" content="摘自本人16年的的博客《Google官方  详解  Android 性能优化【史诗巨著之内存篇】》 博客使用的图片链接服务已经挂掉了，等以后有时间补上。 为什么关注性能# 对于一款APP，用户首先关注的是 app的性能，而不是APP本身的属性功能，用户不关心你是否是搞社交，是否搞电商，是否是一款强大的美图滤镜app，用户首先关注的是 性能—-性能不好，用户会直接卸载，在应用市场给一个恶狠狠得差评，">
<meta property="og:locale">
<meta property="og:image" content="http://cdn.yangchaofan.cn/2222.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/333.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/androidruntimeheap.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/空间预设大小.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc1.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc2.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc3.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc4.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc5.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc6.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/montior.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/montior2.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/heapviewer.gif">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/aee4a58d58a1f48cf83bee00191ac4dc.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc7.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc8.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/b8eeebf564c906276013a33b4db3a7a0.png">
<meta property="og:image" content="http://cdn.yangchaofan.cn/gc9.png">
<meta property="article:published_time" content="2016-06-01T13:34:41.000Z">
<meta property="article:modified_time" content="2021-03-14T05:50:49.396Z">
<meta property="article:author" content="叶金诚">
<meta property="article:tag" content="Android">
<meta property="article:tag" content="Performance">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://cdn.yangchaofan.cn/2222.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"flipBounceYIn","post_header":"perspectiveRightIn","post_body":"fadeIn","coll_header":"swoopIn","sidebar":"shrinkIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idolcoder.gitee.io/blog/2016/06/performance-android/"/>





<!-- 设置文章需要密码访问 -->
<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>

  <title>Android性能优化【史诗巨著之内存篇】 | 叶金诚的站点</title>
  









  

  
	<!-- leafacePlayer -->
	
      <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
      <meta name="baidu-site-verification" content="code-lde50FghqK" />

	

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <!--fork me from github-->
    <a target="_blank" rel="noopener" href="https://github.com/ShaunSheep" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">叶金诚的站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">汇贤雅叙</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-movies">
          <a href="/blog/movies/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-film"></i> <br />
            
            电影
          </a>
        </li>
      
        
        <li class="menu-item menu-item-图书">
          <a href="/blog/books/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            图书
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-links">
          <a href="/blog/links/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-link"></i> <br />
            
            友链
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idolcoder.gitee.io/blog/blog/2016/06/performance-android/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="叶金诚的站点">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Android性能优化【史诗巨著之内存篇】</h2>
        

        <div class="post-meta">
          <span class="post-time">

             

             

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-06-01T21:34:41+08:00">
                2016-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Android/%E5%BA%94%E7%94%A8%E5%B1%82/" itemprop="url" rel="index">
                    <span itemprop="name">应用层</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Android/Performance/" itemprop="url" rel="index">
                    <span itemprop="name">Performance</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/2016/06/performance-android/" class="leancloud_visitors" data-flag-title="Android性能优化【史诗巨著之内存篇】">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">浏览&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          <!--
          
          -->

          
            <span class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数&#58;</span>
                
                <span title="字数">
                  8.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">时长 &asymp;</span>
                
                <span title="时长">
                  36 分钟
                </span>
              
            </span>
          

          <!-- 隐藏文章内标题下，内容描述
          
          -->

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/hint.css/2.4.1/hint.min.css"><p>摘自本人16年的的博客<a target="_blank" rel="noopener" href="http://blog.csdn.net/chivalrousman/article/details/51553114#t16">《Google官方  详解  Android 性能优化【史诗巨著之内存篇】》</a></p>
<p>博客使用的图片链接服务已经挂掉了，等以后有时间补上。</p>
<h1 id="为什么关注性能"><a href="#为什么关注性能" class="headerlink" title="为什么关注性能"></a>为什么关注性能<a href="#为什么关注性能" class="header-anchor">#</a></h1><hr>
<p>对于一款APP，用户首先关注的是 app的性能，而不是APP本身的属性功能，用户不关心你是否是搞社交，是否搞电商，是否是一款强大的美图滤镜app，用户首先关注的是 性能—-<font color="##000000"><strong>性能不好</strong>，用户会直接卸载，在应用市场给一个恶狠狠得差评，小则影响产品口碑，大则影响公司的品牌和声誉，作为程序员，app的性能更应该作为我们关注的一个功能，而不是出了问题 才去门头苦恼加班加点的负担。</font></p>
<p>老实说，提高app性能的确非常难，处理这些问题 你必须知道：</p>
<ol>
<li>应用速度慢的原因</li>
<li>还必须正确使用分析工具来分析数据</li>
</ol>
<p>为此诞生了本文：</p>
<ol>
<li>了解这些工具并用它们找到造成性能不好的原因</li>
<li>从理论角度了解它们</li>
</ol>
<h1 id="如何优化app的性能"><a href="#如何优化app的性能？" class="headerlink" title="如何优化app的性能？"></a>如何优化app的性能？<a href="#如何优化app的性能" class="header-anchor">#</a></h1><hr>
<p>性能优化听上去是一项非常艰巨的功能，但仔细思考，其实非常简单：</p>
<p>1.获取信息</p>
<p>有人说你应用慢，应用闪退（崩掉，crash掉）的时候你需要找到原因。</p>
<p>通过运行 分析和反馈工具软件来收集应用相关的信息，我们需要明确哪些可以测量，哪些可以优化</p>
<p>也就是说任何应用开始优化时，整个过程取决于问题的可测性以及性能优化的可评价性。 开发中经常遇到的坎，问题不可复现，以及对于某一个细节是否需要优化 拿不定主意，这个需要我们自己身处其境 考虑分析各方面因素 得出结论，而不是纯粹得靠感觉。</p>
<p>2.分析数据</p>
<p>很多时候，我们并不能直接理解问题的原因，比如内存溢出（OOM）的error，判断内存溢出需要计算很多个变量得内存大小，我们并不能直观通过眼球看出来一个app 运行过程那些变量的内存，这里我们就需要运行分析工具来帮助我们，将其转化为可视化的图表，</p>
<blockquote>
<p>   在这里，我们可能还是看不懂那些图表，横线竖线，具体是个什么玩意，没有关系，去弄懂它们！就可以成为性能大师了.现在你看那些内存中的二进制转换成图表的过程，就类似于古代的算命大师，步骤1和步骤2 会不断的循环，搜集数据，分析数据···有时候我们不只使用一种搜集工具和分析工具，这就需要自己针对性能得种类来深入研究了</p>
</blockquote>
<p>3.Tack action!</p>
<p> 发现了问题，找到了问题所在以及发生的原因，我们必须要恰当的去解决它，根据项目进度，该性能的优化成本，性能优先级，考虑项目中使用的java库或者android开源框架，其中的一些严格限制，</p>
<p>在你提出方案等待技术委员会评审之前，这些因素都是我们需要考虑的，因为提出的优化方案，不一定会被公司高层接受（除非你就是高层）。</p>
<blockquote>
<p>工具不是规则，理解事物的规则和流程比仅会使用更重要</p>
</blockquote>
<h1 id="为什么关注内存"><a href="#为什么关注内存" class="headerlink" title="为什么关注内存"></a>为什么关注内存<a href="#为什么关注内存" class="header-anchor">#</a></h1><blockquote>
<p>内存大小属于手机性能之一</p>
</blockquote>
<p>举个简单的例子，内存就像你的卧室一样，当你在老家住着动辄几百平的村庄，舒服惯了，突然变卖家产一门心思想创业来到北京，家里的老本只够你住几平米的卫生间的时候，你就会注意到内存【房间】大小的重要性了。</p>
<p>首先我们要知道内存是如何影响系统运行</p>
<p>通常我们认为代码执行速度等同于物理硬件的执行速度，我们的代码指令都是通过使用内存来完成的。通过为实例对象，常量，变量分配内存，来完成操作，但是如何释放这些内存，通常我们并不清楚。</p>
<img src="http://cdn.yangchaofan.cn/2222.png">



<p>一旦分配出去的内存没有及时回收，会引造成系统卡顿，执行操作缓慢现象，这种现象称之为内存泄漏，Memory leak</p>
<img src="http://cdn.yangchaofan.cn/333.png">




<h1 id="java垃圾回收机制官方详解"><a href="#Java垃圾回收机制官方详解" class="headerlink" title="Java垃圾回收机制官方详解"></a>Java垃圾回收机制官方详解<a href="#java垃圾回收机制官方详解" class="header-anchor">#</a></h1><blockquote>
<p>java中的JVM就是一个抽象的计算机，和实际的计算机一样，它具有指令集并使用不同的存储区域，JVM负责执行代码，管理数据，管理内存和寄存器。</p>
</blockquote>
<p>垃圾回收机制只做两件基本的事情：</p>
<ol>
<li> 发现无用的对象</li>
<li> 回收被无用对象占用的内存空间，使得该空间可以被程序再次利用</li>
</ol>
<p>通常，垃圾回收具有如下特点：</p>
<ol>
<li><p>垃圾回收机制的工作目标是回收无用对象的内存空间，这些内存空间都是JVM堆内存的内存资源，对于其他物理资源，比如数据库连接，磁盘I/O 等资源无能为力</p>
</li>
<li><p>为了让垃圾回收机制尽快回收那些对象，可以将该对象引用变量置为null，</p>
</li>
<li><p><font color="#0000FF"><strong>垃圾回收发生的不可预知性</strong></font>，不同JVM 采用不同的算法和机制，有可能定时回收，有可能cpu空闲回收，也有可能内存消耗极限发生，即使通过Runtime对象的gc（），System.gc（）来建议系统进行回收，但这之属于建议，不能精确控制垃圾回收机制的执行,</p>
</li>
</ol>
<pre><code>&gt; 意思就是说，垃圾回收机制什么时候开始执行，并不是我们程序员能控制的，我们只能给予建议。
</code></pre>
<p><font color="#0000FF">那么问题来了，如何精确的进行垃圾回收呢？</font><br><font color="#0000FF">那么问题来了，如何精确的进行垃圾回收呢？</font><br><font color="#0000FF">那么问题来了，如何精确的进行垃圾回收呢？</font></p>
<p>回答很明确，确保每一个对象都进行了有效的释放。对于不再需要的对象，不要引用他们，一旦在别的地方保持对这个对象的引用，垃圾回收机制 暂时不会回收该对象，则会导致严重得问题—-<font color="#FF00FF">系统可用内存越来越少，垃圾回收执行的频率越来越高，cpu全都被垃圾回收的操作占有了，系统性能自然而然就下降了！</font></p>
<p>java8 已经删除了永生代内存，即一些常驻内存，不会回收的数据，而是改为使用本地内存来存储类的元数据，称之为元空间（Metaspace），不过貌似和Android开发没关系(-__-)。</p>
<p>回顾完java垃圾回收，下面介绍<br>##Android 自己的回收机制-Runtime 回收机制</p>
<img src="http://cdn.yangchaofan.cn/androidruntimeheap.png">



<p>经由为数据分配内存的类型，以及系统如何有效的利用gc回收内存，并为新的对象分配内存。</p>
<p>所有要申请的内存都被划分到内存空间中，根据这些特点，哪些数据分配到哪些内存中，取决于Android的版本，</p>
<p>最为重要的一点，Android系统为每个运行中的app分配了预设的内存通常为16m-32m之间，当分配的内存越多，系统内存不足时，系统就可能会执行内存清理，注意，是可能会执行，是否执行垃圾清理是由系统自己判断的。</p>
<p>进行垃圾回收，以确保有足够的内存分配给其他的应用操作，不同的Android版本，会有不同的gc操作，例如在davailk中，gc代表终止程序操作，</p>
<img src="http://cdn.yangchaofan.cn/空间预设大小.png">



<p>##代码是如何影响程序执行的？</p>
<img src="http://cdn.yangchaofan.cn/gc1.png">

<p>上图是正常的界面刷新流程，</p>
<img src="http://cdn.yangchaofan.cn/gc2.png">



<p>上图，gc占据了一大块的时间，对于我们人类来说很短，但是对于系统来说很长了。</p>
<img src="http://cdn.yangchaofan.cn/gc3.png">




<p>综合三张图分析：代码质量很差，使得系统为我们的app分配了过多内存，而且没有及时回收，系统需要更多的时间去执行gc回收，那么系统就没时间去保持界面的活跃，所以就造成了卡顿的现象。，</p>
<blockquote>
<p>在一个循环体中，重复得创建对象，就会造成内存污染，马上就会有很多gc<br>启动，由于这一额外的内存压力，内存泄漏仍然会产生，当可用内存降低到一定总量时，会强制系统gc执行，那循环体中的那部分操作会显示出卡顿的情况，甚至有可能在内存极限的时候，我们开发的应用会闪退。</p>
</blockquote>
<p>所以，唯一的解决办法是：减少代码申请的内存量，不使用的对象及时回收。</p>
<h1 id="memory-monitor"><a href="#Memory-Monitor" class="headerlink" title="Memory Monitor"></a>Memory Monitor<a href="#memory-monitor" class="header-anchor">#</a></h1><img src="http://cdn.yangchaofan.cn/gc4.png">



<p>整个层叠图，代表还有多少内存可用<br>深蓝色区域：代表正在使用的内存大小<br>浅灰色区域：代表空闲未分配内存</p>
<img src="http://cdn.yangchaofan.cn/gc5.png">



<p>这个红色箭头所指的坡度表示急需大量的内存，内存分配也急剧的增加。<br>上图是一个内存管理良好的例子</p>
<p>下图我们看一个内存糟糕的例子</p>
<img src="http://cdn.yangchaofan.cn/gc6.png">



<blockquote>
<p>分析</p>
</blockquote>
<p><font color="#fff22f22">这里有一部分代码占用了大量的内存，然后又一下子释放了内存，生成不断重复又窄又长的曲线，这就是程序在花大量的时间在进行垃圾清理，运行垃圾清理的时间越多，其他操作可用的时间就越少，比如跟网络交互数据，页面刷新，打电话，听歌等等，这样就造成了卡顿<font></font></font></p>
<p>###<strong>使用Montior过程中遇到的 No Debugable Application的问题</strong></p>
<img src="http://cdn.yangchaofan.cn/montior.png">




<blockquote>
<p>solution：Tools-Android-Android adb interact</p>
<p>最初并不会见效，重启app即可，</p>
</blockquote>
<img src="http://cdn.yangchaofan.cn/montior2.png">

<h1 id="内存泄漏"><a href="#内存泄漏" class="headerlink" title="内存泄漏"></a>内存泄漏<a href="#内存泄漏" class="header-anchor">#</a></h1><hr>
<p>在这里我才开始引入内存泄漏的原因【虽然文章前面已经提到，但是在这里才着重拿出来作为一节】</p>
<p>网络上和一些书籍对内存泄漏解释是 应该回收的对象没有回收，有点不全面，我认为深一点来说，内存泄漏是针对系统而言的，内存泄漏指的是不能被使用的内存，但是垃圾回收器无法识别出来，对其进行回收，这些对象一直存在于堆中，并且持续占据着内存空间，无法被删除，随着不断泄漏，系统可用的内存就越来越小，意味着系统又需要花更多的时间 去进行内存清理操作，进行垃圾回收操作的次数越来越多，</p>
<blockquote>
<p>简单的内存泄漏：对没有使用的对象 循环引用<br>复杂一点的：在listview还没有绘制完成时就添加到activity  &gt;</p>
</blockquote>
<h1 id="heap-viewer"><a href="#Heap-Viewer" class="headerlink" title="Heap Viewer"></a>Heap Viewer<a href="#heap-viewer" class="header-anchor">#</a></h1><blockquote>
<p>Heap viewer使用步骤，我录制了gift图，详情请看：</p>
</blockquote>
<img src="http://cdn.yangchaofan.cn/heapviewer.gif">



<blockquote>
<p> 了解Heap Viewer:<br> Heap Viewer可以有效的分析程序在堆中分配的数据类型及数量和 大小小</p>
</blockquote>
<p> <img src="https://img-blog.csdnimg.cn/img_convert/aee4a58d58a1f48cf83bee00191ac4dc.png" alt="这里写图片描述">  </p>
<blockquote>
<p>  这里表示 byte数组和boolean数组的数量为177，占用了1.423M的内存</p>
</blockquote>
<p>#内存泄漏的情况</p>
<img src="http://cdn.yangchaofan.cn/gc7.png">



<p>绿色箭头标出来的那部分 代码就是有问题的部分，原因在于，可以内存几乎为0，所有的内存已经被程序占用，首先记住，我们的代码有问题，造成了内存泄漏，并且，垃圾回收机制无法回收那部分内存空间</p>
<p>下图为30s之后的内存回收情况</p>
<img src="http://cdn.yangchaofan.cn/gc8.png">



<p>启动第二次gc，此时Android调整并提高应用的内存上限，这样做的同时，如果漏洞没有修复，表明内存泄漏仍然存在，那么还会有第三次，第四次同样的gc操作，直至系统无法调整提高给应用更高的内存上限，造成内存溢出，甚至可能死机，</p>
<p>#Trace Viewer分配追踪器<br>  <img src="https://img-blog.csdnimg.cn/img_convert/b8eeebf564c906276013a33b4db3a7a0.png" alt="这里写图片描述"></p>
<blockquote>
<blockquote>
<p>Trace Viewer可以精确追踪到代码的位置，限于篇幅请按照上图点击 那几个按钮  自行摸索考功它的功能能</p>
</blockquote>
</blockquote>
<h1 id="高效加载图片图片"><a href="#高效加载图片图片" class="headerlink" title="高效加载图片图片"></a>高效加载图片图片<a href="#高效加载图片图片" class="header-anchor">#</a></h1><h2 id="为什么只关注图片加载而不去处理其他数据来解决内存不足的问题"><a href="#为什么只关注图片加载，而不去处理其他数据来解决内存不足的问题？" class="headerlink" title="为什么只关注图片加载，而不去处理其他数据来解决内存不足的问题？"></a><strong>为什么只关注图片加载，而不去处理其他数据来解决内存不足的问题？</strong><a href="#为什么只关注图片加载而不去处理其他数据来解决内存不足的问题" class="header-anchor">#</a></h2><ol>
<li><p>Android 加载图片会创建Bitmap,drawable实例，占用内存空间，如果不进行高效处理，程序会很快达到 Android系统分配给APP的内存上限，直至挂掉</p>
</li>
<li><p>图片资源相比文本资源，在内存中会占据更大的内存，从字节数就可以看出来</p>
</li>
<li><p>在我们的应用中正确恰当高效的加载 图片资源 是一件非常棘手的事情</p>
</li>
</ol>
<blockquote>
<ol>
<li>Android 系统会分配给单个APP至少 16M左右的内存，） Android Compatibility Definition Document (CDD)中，根据不同手机的尺寸和屏幕像素来要求应用最小内存，我们开发 的应用需要优化内存至最低内存限制，然而请记住，许多手机对内存有着更高的要求。</li>
<li>图片消耗大量的内存，尤其是高像素的图片，比如入门级单反相机拍摄出来的一张图片，都有可能超出APP的最低内存限制</li>
<li>app 中一些常见的UI 比如 ListView, GridView and ViewPager，都需要立刻加载大量的图片，注意是立刻，这对内存管理提出了很高的要求。</li>
</ol>
</blockquote>
<p><strong>所以我们需要高效得加载图片。</strong></p>
<h1 id="高效的加载大图"><a href="#高效的加载大图：" class="headerlink" title="高效的加载大图："></a>高效的加载大图：<a href="#高效的加载大图" class="header-anchor">#</a></h1><p>一张图片的像素，尺寸，分别率，由可能超过Android的UI组件本身大小，UI组件的大小是由手机设备屏幕决定的，这些超出的部分，会消耗更多的内存。</p>
<p>应该让图片去匹配我们的手机设备，所以，我们需要对图片进行处理：</p>
<ol>
<li>不能超过每个应用程序的内存限制</li>
<li>用最小的内存加载图片</li>
</ol>
<h2 id="只需三步"><a href="#只需三步" class="headerlink" title="只需三步"></a>只需三步<a href="#只需三步" class="header-anchor">#</a></h2><h2 id="1-读取内存中bitmap的尺寸和类型"><a href="#1-读取内存中Bitmap的尺寸和类型" class="headerlink" title="1. 读取内存中Bitmap的尺寸和类型"></a><strong>1. 读取内存中Bitmap的尺寸和类型</strong><a href="#1-读取内存中bitmap的尺寸和类型" class="header-anchor">#</a></h2><p> BitmapFactory类提供了很多解析Bitmap的方法（decodeByteArray(), decodeFile(), decodeResource(), etc.），每一种解析方法都有一个额外的参数 BitmapFactory.Options，设置inJustDecodeBounds 属性为true可以禁止应用分配内存，此时bitmap返回为null，但是我们可以通过BitmapFactory.Options对象来获取很多有用的参数</p>
<p> 此时 你可以通过BitmapFactory.Options来读取图片的尺寸和类型</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</span><br><span class="line">options.inJustDecodeBounds = <span class="keyword">true</span>;</span><br><span class="line">BitmapFactory.decodeResource(getResources(), R.id.myimage, options);</span><br><span class="line"><span class="keyword">int</span> imageHeight = options.outHeight;</span><br><span class="line"><span class="keyword">int</span> imageWidth = options.outWidth;</span><br><span class="line">String imageType = options.outMimeType;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>总结：为了避免java.lang.OutOfMemory ，在加载图片之前需要检查原图的大小是否超出最低内存限制。</p>
</blockquote>
<h2 id="2-加载一张小图使得系统分配较少的内存给它"><a href="#2-加载一张小图，使得系统分配较少的内存给它。" class="headerlink" title="2. 加载一张小图，使得系统分配较少的内存给它。"></a><strong>2. 加载一张小图，使得系统分配较少的内存给它。</strong><a href="#2-加载一张小图使得系统分配较少的内存给它" class="header-anchor">#</a></h2><blockquote>
<p>现在我们已经获取到了图片的尺寸，加载一张图片之前，我们需要考虑：</p>
</blockquote>
<ul>
<li><p>计算整张图片需要多大的内存</p>
</li>
<li><p>我们希望给它多大的内存</p>
</li>
<li><p>加载图片的组件比如Imageview的尺寸是多大</p>
</li>
<li><p>当前手机设备的屏幕尺寸和分辨率</p>
</li>
</ul>
<p>例如一张1080<em>720的图片要展示在一个128</em>72的Imageview上</p>
<p>实际 项目中，比如一张2048x1536的图片，我们通过设置inSampleSize为4，来创建实际大小为512x384的bitmap，这样需要的内存为0.75MB而不是之前的12MB（色彩模式都是ARGB_8888的情况下），</p>
<p>Google官方提供了两个方法来供我们使用，可以封装到自己的工具类中：</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateInSampleSize</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            BitmapFactory.Options options, <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获得内存中图片的宽高</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> height = options.outHeight;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> width = options.outWidth;</span><br><span class="line">    <span class="keyword">int</span> inSampleSize = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (height &gt; reqHeight || width &gt; reqWidth) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> halfHeight = height / <span class="number">2</span>;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> halfWidth = width / <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 计算出一个数值，必须符合为2的幂（1，2，4，8，tec），赋值给inSampleSize</span></span><br><span class="line">        <span class="comment">// 图片宽高应大于期望的宽高的时候，才进行计算</span></span><br><span class="line">        <span class="keyword">while</span> ((halfHeight / inSampleSize) &gt; reqHeight</span><br><span class="line">                &amp;&amp; (halfWidth / inSampleSize) &gt; reqWidth) &#123;</span><br><span class="line">            inSampleSize *= <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> inSampleSize;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Bitmap <span class="title">decodeSampledBitmapFromResource</span><span class="params">(Resources res, <span class="keyword">int</span> resId,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 第一次解析 inJustDecodeBounds=true 只是用来获取bitmap在内存中的尺寸和类型，系统并不会为其分配内存，</span></span><br><span class="line">    <span class="keyword">final</span> BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</span><br><span class="line">    options.inJustDecodeBounds = <span class="keyword">true</span>;</span><br><span class="line">    BitmapFactory.decodeResource(res, resId, options);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 计算出一个数值</span></span><br><span class="line">    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 根据inSampleSize 数值来解析bitmap</span></span><br><span class="line">    options.inJustDecodeBounds = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">return</span> BitmapFactory.decodeResource(res, resId, options);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>研究一个新的函数，我们先关注函数的输入和输出提高阅读能力</p>
</blockquote>
<h2 id="3接着为我们的ui组件imageview设置一张缩略图咯"><a href="#3-接着为我们的UI组件ImageView设置一张缩略图咯：" class="headerlink" title="3.接着为我们的UI组件ImageView设置一张缩略图咯："></a><strong>3.接着为我们的UI组件ImageView设置一张缩略图咯：</strong><a href="#3接着为我们的ui组件imageview设置一张缩略图咯" class="header-anchor">#</a></h2><div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mImageView.setImageBitmap(</span><br><span class="line">    decodeSampledBitmapFromResource(getResources(), R.id.myimage, <span class="number">100</span>, <span class="number">100</span>));</span><br></pre></td></tr></table></figure></div>
<p>为了完全理解这一部分，初学者请自行查阅</p>
<ol>
<li> BitmapFactory.decode   </li>
<li> BitmapFactory.Options</li>
</ol>
<h1 id="使asynctask加载bitmap"><a href="#使AsyncTask加载Bitmap" class="headerlink" title="使AsyncTask加载Bitmap"></a>使AsyncTask加载Bitmap<a href="#使asynctask加载bitmap" class="header-anchor">#</a></h1><p>当图片资源来自网络或者硬盘的时候，最好不要直接在主线程中加载它，例如IO资源或者数据库资源都会占用CPU，CPU 要做的事情过多，Android手机会造成卡顿得现象，</p>
<p><strong>好在Google 提供了解决办法–AsyncTask异步加载工具</strong></p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BitmapWorkerTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">Integer</span>, <span class="title">Void</span>, <span class="title">Bitmap</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> WeakReference&lt;ImageView&gt; imageViewReference;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> data = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BitmapWorkerTask</span><span class="params">(ImageView imageView)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 用弱引用确保能被垃圾回收机制回收</span></span><br><span class="line">        imageViewReference = <span class="keyword">new</span> WeakReference&lt;ImageView&gt;(imageView);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在后台解析bitmap</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Bitmap <span class="title">doInBackground</span><span class="params">(Integer... params)</span> </span>&#123;</span><br><span class="line">        data = params[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">return</span> decodeSampledBitmapFromResource(getResources(), data, <span class="number">100</span>, <span class="number">100</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 一旦完成，imageView将会加载bitmap</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPostExecute</span><span class="params">(Bitmap bitmap)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (imageViewReference != <span class="keyword">null</span> &amp;&amp; bitmap != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">final</span> ImageView imageView = imageViewReference.get();</span><br><span class="line">            <span class="keyword">if</span> (imageView != <span class="keyword">null</span>) &#123;</span><br><span class="line">                imageView.setImageBitmap(bitmap);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>

<p>接着我们在主线程中执行它即可</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">    BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(imageView);</span><br><span class="line">    task.execute(resId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<h1 id="使用lrucache缓存图片"><a href="#使用Lrucache缓存图片" class="headerlink" title="使用Lrucache缓存图片"></a>使用Lrucache缓存图片<a href="#使用lrucache缓存图片" class="header-anchor">#</a></h1><p><font size="4"><strong>1.  为什么要缓存图片？</strong><font></font></font></p>
<p>对于如何高效的加载一张图片 ，我们似乎已经得心应手了，这里要泼一盆凉水给大家，因为我们的应用不仅只是加载一张图片这么简单，比如ListView, GridView or ViewPager，RecyclerView，需要立刻加载出大量的bitmap，滑动的过程不断加载bitmap，还要求不卡顿，内存够用，这似乎又是一件棘手的事情。</p>
<p>Google 又提供了一种解决思路：对于ListView，RecyclerView，有可见的item和不可见的item，回收不可见的item  内存，分配给可见的，这样内存得到了重复利用，避免重复创建对象，不断申请并分配新的内存空间，触发最低内存限制的危险。</p>
<p>所以我们要管理 这些 已经创建好的内存。</p>
<p><font size="4"><strong>2.  使用内存缓存</strong><font></font></font></p>
<ol>
<li><p>为什么优先使用内存缓存？ </p>
<p>答：相比硬盘缓存的读取速度，读取内存中的数据更快</p>
</li>
<li><p>Google官方有什么建议？  </p>
<p>答：Google推荐Lrucache类，底层使用用强引用封装的LinkedHashMap，来存储最近使用的对象，它自动会回收最近使用的对象当中，使用的最少的那一个对象的内存，这一点毋庸置疑值得推荐！</p>
</li>
</ol>
<blockquote>
<p>一种过时的做法，是用虚引用或者弱引用来标记bitmap，这种方法在Android 3.0以后已经不提倡了，因为类似JDK1.8那样，bitmap的内存是放在本地内存中的，它的回收是不确定的，有可能导致APP挂掉，切勿使用。 </p>
</blockquote>
<ol start="3">
<li><p>Lrucache这么棒，我们该如何用？</p>
<p>Lrucache就可以当作一种存储数据的结构，类似list，set，可以存储对象，获取对象，对应的有add（） 和get（）方法，它与数组一样，初始化的时候需要指定一个初始的大小。</p>
<p>那么Lrucache实例 初始的大小该如何确定？<br>在计算大小之前，我们需要明确几件事情：</p>
</li>
</ol>
<ul>
<li><p>我们的Activity和Application还有多少可用内存？</p>
</li>
<li><p>我们的Activity和Application还有多少可用内存？</p>
</li>
<li><p>第一次加载的时候，需要为多少图片分配内存？可见的item数量，决定了图片的数量，图片的数量*每张图片的内存大小就是初始化需要分配的内存。</p>
</li>
<li><p>用户当前手机的屏幕尺寸和屏幕密度（为什么要这俩参数？大屏幕手机 ，初始化的时候会加载更多的item，需要的内存更大）</p>
</li>
<li><p>这张图片我们要怎样配置？图片的尺寸如何设置，颜色模式如何配置？根据不同的需求，比如是做用户头像，还是信息展示？都有各自的应用场景的要求。我们需要分类判断.</p>
</li>
<li><p>cache大小是由内存大小决定的，而不是 它存储数据的个数决定</p>
<blockquote>
<p>这让我想起一个在项目开发中常见的bug，use a bitmap which has bean recycler</p>
</blockquote>
<p> <font size="4"><strong>4. Lrucache使用实例</strong><font>     </font></font></p>
</li>
</ul>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> LruCache&lt;String, Bitmap&gt; mMemoryCache;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// 当Lrucache使用的内存大小超过虚拟机最大的可用内存时候，Android会抛出OutOfMemory exception</span></span><br><span class="line">  </span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> maxMemory = (<span class="keyword">int</span>) (Runtime.getRuntime().maxMemory() / <span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 使用虚拟机可用1/8</span></span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> cacheSize = maxMemory / <span class="number">8</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//  在Lrucache构造函数中初始化它的大小</span></span><br><span class="line">    <span class="comment">// int in its constructor</span></span><br><span class="line">    mMemoryCache = <span class="keyword">new</span> LruCache&lt;String, Bitmap&gt;(cacheSize) &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">sizeOf</span><span class="params">(String key, Bitmap bitmap)</span> </span>&#123;</span><br><span class="line">     </span><br><span class="line">     <span class="comment">//cache大小是由内存大小决定的，而不是 它存储数据的个数决定</span></span><br><span class="line">         <span class="keyword">return</span> bitmap.getByteCount() / <span class="number">1024</span>;</span><br><span class="line">        &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addBitmapToMemoryCache</span><span class="params">(String key, Bitmap bitmap)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (getBitmapFromMemCache(key) == <span class="keyword">null</span>) &#123;</span><br><span class="line">        mMemoryCache.put(key, bitmap);</span><br><span class="line">        &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Bitmap <span class="title">getBitmapFromMemCache</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> mMemoryCache.get(key);</span><br><span class="line">&#125;  </span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p>loadBitmap的过程很简洁：如果内存缓存中有这张bitmap，则直接刷新imageview，如果bitmap为空，则启动后台线程去加载bitmap，接着刷新imageview</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> String imageKey = String.valueOf(resId);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> Bitmap bitmap = getBitmapFromMemCache(imageKey);</span><br><span class="line">    <span class="keyword">if</span> (bitmap != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mImageView.setImageBitmap(bitmap);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        mImageView.setImageResource(R.drawable.image_placeholder);</span><br><span class="line">        BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(mImageView);</span><br><span class="line">        task.execute(resId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;  </span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p>异步线程  BitmapWorkerTask</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BitmapWorkerTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">Integer</span>, <span class="title">Void</span>, <span class="title">Bitmap</span>&gt; </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// Decode image in background.</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Bitmap <span class="title">doInBackground</span><span class="params">(Integer... params)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Bitmap bitmap = decodeSampledBitmapFromResource(</span><br><span class="line">                getResources(), params[<span class="number">0</span>], <span class="number">100</span>, <span class="number">100</span>));</span><br><span class="line">        addBitmapToMemoryCache(String.valueOf(params[<span class="number">0</span>]), bitmap);</span><br><span class="line">        <span class="keyword">return</span> bitmap;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><font size="4"><strong>5. 磁盘缓存</strong><font><br>与内存缓存相结合的还有磁盘缓存，虽然磁盘读取速度较慢，但是持久存储的，不像内存缓存那样，在内存极限情况下仍然会被清理，比如后台正在执行数据加载，突然打进来一个电话，内存不足系统可能会进行垃圾回收。缓存就没有了</font></font></p>
<p>Google官方提供直接DiskLruCache 类</p>
<p>为什么要使用DiskLruCache 很明了：就是解决当内存缓存不可用的情形</p>
<blockquote>
<p>内当需要频繁访问缓存的图片资源时，比如APP的画廊功能，可以考虑使用ContentProvider解决更为妥当。</p>
</blockquote>
<p>下面是它的源码</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> DiskLruCache mDiskLruCache;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Object mDiskCacheLock = <span class="keyword">new</span> Object();</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">boolean</span> mDiskCacheStarting = <span class="keyword">true</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DISK_CACHE_SIZE = <span class="number">1024</span> * <span class="number">1024</span> * <span class="number">10</span>; <span class="comment">// 10MB</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String DISK_CACHE_SUBDIR = <span class="string">&quot;thumbnails&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// Initialize memory cache</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// Initialize disk cache on background thread</span></span><br><span class="line">    File cacheDir = getDiskCacheDir(<span class="keyword">this</span>, DISK_CACHE_SUBDIR);</span><br><span class="line">    <span class="keyword">new</span> InitDiskCacheTask().execute(cacheDir);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InitDiskCacheTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">File</span>, <span class="title">Void</span>, <span class="title">Void</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Void <span class="title">doInBackground</span><span class="params">(File... params)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (mDiskCacheLock) &#123;</span><br><span class="line">            File cacheDir = params[<span class="number">0</span>];</span><br><span class="line">            mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE);</span><br><span class="line">            mDiskCacheStarting = <span class="keyword">false</span>; <span class="comment">// Finished initialization</span></span><br><span class="line">            mDiskCacheLock.notifyAll(); <span class="comment">// Wake any waiting threads</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BitmapWorkerTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">Integer</span>, <span class="title">Void</span>, <span class="title">Bitmap</span>&gt; </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// Decode image in background.</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Bitmap <span class="title">doInBackground</span><span class="params">(Integer... params)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> String imageKey = String.valueOf(params[<span class="number">0</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Check disk cache in background thread</span></span><br><span class="line">        Bitmap bitmap = getBitmapFromDiskCache(imageKey);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (bitmap == <span class="keyword">null</span>) &#123; <span class="comment">// Not found in disk cache</span></span><br><span class="line">            <span class="comment">// Process as normal</span></span><br><span class="line">            <span class="keyword">final</span> Bitmap bitmap = decodeSampledBitmapFromResource(</span><br><span class="line">                    getResources(), params[<span class="number">0</span>], <span class="number">100</span>, <span class="number">100</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Add final bitmap to caches</span></span><br><span class="line">        addBitmapToCache(imageKey, bitmap);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> bitmap;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addBitmapToCache</span><span class="params">(String key, Bitmap bitmap)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Add to memory cache as before</span></span><br><span class="line">    <span class="keyword">if</span> (getBitmapFromMemCache(key) == <span class="keyword">null</span>) &#123;</span><br><span class="line">        mMemoryCache.put(key, bitmap);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Also add to disk cache</span></span><br><span class="line">    <span class="keyword">synchronized</span> (mDiskCacheLock) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mDiskLruCache != <span class="keyword">null</span> &amp;&amp; mDiskLruCache.get(key) == <span class="keyword">null</span>) &#123;</span><br><span class="line">            mDiskLruCache.put(key, bitmap);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Bitmap <span class="title">getBitmapFromDiskCache</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span> (mDiskCacheLock) &#123;</span><br><span class="line">        <span class="comment">// Wait while disk cache is started from background thread</span></span><br><span class="line">        <span class="keyword">while</span> (mDiskCacheStarting) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                mDiskCacheLock.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (mDiskLruCache != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> mDiskLruCache.get(key);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Creates a unique subdirectory of the designated app cache directory. Tries to use external</span></span><br><span class="line"><span class="comment">// but if not mounted, falls back on internal storage.</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> File <span class="title">getDiskCacheDir</span><span class="params">(Context context, String uniqueName)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Check if media is mounted or storage is built-in, if so, try and use external cache dir</span></span><br><span class="line">    <span class="comment">// otherwise use internal cache dir</span></span><br><span class="line">    <span class="keyword">final</span> String cachePath =</span><br><span class="line">            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||</span><br><span class="line">                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :</span><br><span class="line">                            context.getCacheDir().getPath();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> File(cachePath + File.separator + uniqueName);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></div>
<p> <strong>6.处理运行时变更的缓存</strong><br>当屏幕旋转，或者其他原因导致Activity  restart，这个时候难道又让我们重新创建大量的图像资源？<br>回答是否定的，Google提供了一种解决方案：</p>
<p>通过在Activity中使用fragment，构造Fragment时，通过设置 setRetainInstance(true))来设置缓存，<br>话不多说，直接上代码：</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> LruCache&lt;String, Bitmap&gt; mMemoryCache;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    RetainFragment retainFragment =</span><br><span class="line">            RetainFragment.findOrCreateRetainFragment(getFragmentManager());</span><br><span class="line">    mMemoryCache = retainFragment.mRetainedCache;</span><br><span class="line">    <span class="keyword">if</span> (mMemoryCache == <span class="keyword">null</span>) &#123;</span><br><span class="line">        mMemoryCache = <span class="keyword">new</span> LruCache&lt;String, Bitmap&gt;(cacheSize) &#123;</span><br><span class="line">            ... <span class="comment">// Initialize cache here as usual</span></span><br><span class="line">        &#125;</span><br><span class="line">        retainFragment.mRetainedCache = mMemoryCache;</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RetainFragment</span> <span class="keyword">extends</span> <span class="title">Fragment</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">&quot;RetainFragment&quot;</span>;</span><br><span class="line">    <span class="keyword">public</span> LruCache&lt;String, Bitmap&gt; mRetainedCache;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RetainFragment</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RetainFragment <span class="title">findOrCreateRetainFragment</span><span class="params">(FragmentManager fm)</span> </span>&#123;</span><br><span class="line">        RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);</span><br><span class="line">        <span class="keyword">if</span> (fragment == <span class="keyword">null</span>) &#123;</span><br><span class="line">            fragment = <span class="keyword">new</span> RetainFragment();</span><br><span class="line">            fm.beginTransaction().add(fragment, TAG).commit();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> fragment;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        setRetainInstance(<span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>尊重博主原创，如需转载，请附上本文链接接：<br><a target="_blank" rel="noopener" href="http://blog.csdn.net/chivalrousman/article/details/51567118">http://blog.csdn.net/chivalrousman/article/details/51567118</a></p>
</blockquote>
<h1 id="补充-ui组件并发性问题"><a href="#补充-UI组件并发性问题" class="headerlink" title="补充-UI组件并发性问题"></a>补充-UI组件并发性问题<a href="#补充-ui组件并发性问题" class="header-anchor">#</a></h1><p>这一部分涉及到UI细节，例如ListView，Viewpager的优化</p>
<h1 id="viewpager"><a href="#ViewPager" class="headerlink" title="ViewPager"></a>ViewPager<a href="#viewpager" class="header-anchor">#</a></h1><p>ViewPager是一个非常棒的组件，通过使用ViewPager和PagerAdapter可以实现类似新闻标题的滑动条以及常见的画廊功能。</p>
<p>谈到优化，Google 建议使用 PagerAdapter的子类FragmentStatePagerAdapter ，它可以在后台自动销毁和保存ViewPager中使用的Fragment的数据，通过使用它可以节省内存开销。</p>
<blockquote>
<p>Note：当然，如果我们可以使用PagerAdapter来完成少许图片资源的展示，毕竟我们的优化是为了节省内存开销。</p>
</blockquote>
<p>下面实例展示了带有ImageView的ViewPager，在主activity持有ViewPager和它的适配器。</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageDetailActivity</span> <span class="keyword">extends</span> <span class="title">FragmentActivity</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String EXTRA_IMAGE = <span class="string">&quot;extra_image&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ImagePagerAdapter mAdapter;</span><br><span class="line">    <span class="keyword">private</span> ViewPager mPager;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// A static dataset to back the ViewPager adapter</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> Integer[] imageResIds = <span class="keyword">new</span> Integer[] &#123;</span><br><span class="line">            R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,</span><br><span class="line">            R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,</span><br><span class="line">            R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.image_detail_pager); <span class="comment">// Contains just a ViewPager</span></span><br><span class="line"></span><br><span class="line">        mAdapter = <span class="keyword">new</span> ImagePagerAdapter(getSupportFragmentManager(), imageResIds.length);</span><br><span class="line">        mPager = (ViewPager) findViewById(R.id.pager);</span><br><span class="line">        mPager.setAdapter(mAdapter);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ImagePagerAdapter</span> <span class="keyword">extends</span> <span class="title">FragmentStatePagerAdapter</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> mSize;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">ImagePagerAdapter</span><span class="params">(FragmentManager fm, <span class="keyword">int</span> size)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">super</span>(fm);</span><br><span class="line">            mSize = size;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> mSize;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Fragment <span class="title">getItem</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> ImageDetailFragment.newInstance(position);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>在适配器的getItem中使用了自定义的Fragment，它持有ImageView，并负责完成展示</p>
<h2 id="看上去已经大功告成-了但事实真的如此吗"><a href="#看上去已经大功告成-了，但事实真的如此吗？" class="headerlink" title="看上去已经大功告成 了，但事实真的如此吗？"></a>看上去已经大功告成 了，但事实真的如此吗？<a href="#看上去已经大功告成-了但事实真的如此吗" class="header-anchor">#</a></h2><p>下面是ImageDetailFragment的细节，通过ImageDetailFragment，看上去已经大功告成 了，但事实真的如此吗？</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageDetailFragment</span> <span class="keyword">extends</span> <span class="title">Fragment</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String IMAGE_DATA_EXTRA = <span class="string">&quot;resId&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> mImageNum;</span><br><span class="line">    <span class="keyword">private</span> ImageView mImageView;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> ImageDetailFragment <span class="title">newInstance</span><span class="params">(<span class="keyword">int</span> imageNum)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> ImageDetailFragment f = <span class="keyword">new</span> ImageDetailFragment();</span><br><span class="line">        <span class="keyword">final</span> Bundle args = <span class="keyword">new</span> Bundle();</span><br><span class="line">        args.putInt(IMAGE_DATA_EXTRA, imageNum);</span><br><span class="line">        f.setArguments(args);</span><br><span class="line">        <span class="keyword">return</span> f;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Empty constructor, required as per Fragment docs</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ImageDetailFragment</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        mImageNum = getArguments() != <span class="keyword">null</span> ? getArguments().getInt(IMAGE_DATA_EXTRA) : -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> View <span class="title">onCreateView</span><span class="params">(LayoutInflater inflater, ViewGroup container,</span></span></span><br><span class="line"><span class="function"><span class="params">            Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// image_detail_fragment.xml contains just an ImageView</span></span><br><span class="line">        <span class="keyword">final</span> View v = inflater.inflate(R.layout.image_detail_fragment, container, <span class="keyword">false</span>);</span><br><span class="line">        mImageView = (ImageView) v.findViewById(R.id.imageView);</span><br><span class="line">        <span class="keyword">return</span> v;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onActivityCreated</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onActivityCreated(savedInstanceState);</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> resId = ImageDetailActivity.imageResIds[mImageNum];</span><br><span class="line">        mImageView.setImageResource(resId); <span class="comment">//为ImageView设置图片</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>阅读一段代码，除了学习外，还要思考它有什么缺点，如果是我，我该如何提高。</p>
</blockquote>
<p>希望你能注意到这些问题，上述代码是在UI线程中加载的，可能会导致我们开发的应用长时间无响应而被迫挂掉。所以，请使用AsyncTask开启子线程来加载图片：</p>
<blockquote>
<p>在阅读这段代码之前，请首先阅读上一篇博文 内存优化中的AsyncTsak部分</p>
</blockquote>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageDetailActivity</span> <span class="keyword">extends</span> <span class="title">FragmentActivity</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">        mImageView.setImageResource(R.drawable.image_placeholder);</span><br><span class="line">        BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(mImageView);</span><br><span class="line">        task.execute(resId);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ... <span class="comment">// include BitmapWorkerTask class，</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageDetailFragment</span> <span class="keyword">extends</span> <span class="title">Fragment</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onActivityCreated</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onActivityCreated(savedInstanceState);</span><br><span class="line">        <span class="keyword">if</span> (ImageDetailActivity.class.isInstance(getActivity())) &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">int</span> resId = ImageDetailActivity.imageResIds[mImageNum];</span><br><span class="line">            <span class="comment">// 使用子线程来加载图片</span></span><br><span class="line">            ((ImageDetailActivity) getActivity()).loadBitmap(resId, mImageView);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p> 请至少阅读完上一篇内存优化的LruCache部分才能保证你理解这里</p>
</blockquote>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageDetailActivity</span> <span class="keyword">extends</span> <span class="title">FragmentActivity</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">private</span> LruCache&lt;String, Bitmap&gt; mMemoryCache;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">        <span class="comment">// initialize LruCache</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> String imageKey = String.valueOf(resId);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> Bitmap bitmap = mMemoryCache.get(imageKey);</span><br><span class="line">        <span class="keyword">if</span> (bitmap != <span class="keyword">null</span>) &#123;</span><br><span class="line">            mImageView.setImageBitmap(bitmap);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            mImageView.setImageResource(R.drawable.image_placeholder);</span><br><span class="line">            BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(mImageView);</span><br><span class="line">            task.execute(resId);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ... <span class="comment">// include updated BitmapWorkerTask </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>注意，只有阅读完上一篇内存优化中的Lrucache部分和AsyncTask部分才能保证你完全读懂上述代码</p>
</blockquote>
<h1 id="recyclerviewgridviewlistview"><a href="#RecyclerView，GridView，ListView" class="headerlink" title="RecyclerView，GridView，ListView"></a>RecyclerView，GridView，ListView<a href="#recyclerviewgridviewlistview" class="header-anchor">#</a></h1><p>下面可能是大家经常的做法：</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageGridFragment</span> <span class="keyword">extends</span> <span class="title">Fragment</span> <span class="keyword">implements</span> <span class="title">AdapterView</span>.<span class="title">OnItemClickListener</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> ImageAdapter mAdapter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// A static dataset to back the GridView adapter</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> Integer[] imageResIds = <span class="keyword">new</span> Integer[] &#123;</span><br><span class="line">            R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,</span><br><span class="line">            R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,</span><br><span class="line">            R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Empty constructor as per Fragment docs</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ImageGridFragment</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        mAdapter = <span class="keyword">new</span> ImageAdapter(getActivity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> View <span class="title">onCreateView</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> View v = inflater.inflate(R.layout.image_grid_fragment, container, <span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">final</span> GridView mGridView = (GridView) v.findViewById(R.id.gridView);</span><br><span class="line">        mGridView.setAdapter(mAdapter);</span><br><span class="line">        mGridView.setOnItemClickListener(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">return</span> v;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onItemClick</span><span class="params">(AdapterView&lt;?&gt; parent, View v, <span class="keyword">int</span> position, <span class="keyword">long</span> id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Intent i = <span class="keyword">new</span> Intent(getActivity(), ImageDetailActivity.class);</span><br><span class="line">        i.putExtra(ImageDetailActivity.EXTRA_IMAGE, position);</span><br><span class="line">        startActivity(i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageAdapter</span> <span class="keyword">extends</span> <span class="title">BaseAdapter</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> Context mContext;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">ImageAdapter</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">super</span>();</span><br><span class="line">            mContext = context;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> imageResIds.length;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">getItem</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> imageResIds[position];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getItemId</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> position;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> View <span class="title">getView</span><span class="params">(<span class="keyword">int</span> position, View convertView, ViewGroup container)</span> </span>&#123;</span><br><span class="line">            ImageView imageView;</span><br><span class="line">            <span class="keyword">if</span> (convertView == <span class="keyword">null</span>) &#123; <span class="comment">// if it&#x27;s not recycled, initialize some attributes</span></span><br><span class="line">                imageView = <span class="keyword">new</span> ImageView(mContext);</span><br><span class="line">                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);</span><br><span class="line">                imageView.setLayoutParams(<span class="keyword">new</span> GridView.LayoutParams(</span><br><span class="line">                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                imageView = (ImageView) convertView;</span><br><span class="line">            &#125;</span><br><span class="line">            imageView.setImageResource(imageResIds[position]); <span class="comment">// Load image into ImageView</span></span><br><span class="line">            <span class="keyword">return</span> imageView;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>看上去非常棒，对吗？但是我们如何才能做的更好？</p>
<p>如果你能发现主线程加载图片的问题，恭喜你，有一点点进步。但是重复提醒你使用AsyncTask，显然不是我写这一节的目的。</p>
<p>我们还需要警惕GridView 中的<strong>并发</strong>问题，因为iGridView 会回收子View的内存空间。</p>
<h2 id="并发问题"><a href="#并发问题" class="headerlink" title="并发问题"></a>并发问题<a href="#并发问题" class="header-anchor">#</a></h2><p>像ListView和GridView，与RecyclerView使用AsyncTask的时候，不能忽视一个问题：Android系统为了高效分配内存，这些组件都会在上下滑动的时候回收子view的内存。在滑动的时候，并不能保证AsyncTask可以完成当前任务。此外，也不能保证异步任务可以按照顺序完成。</p>
<p>Google在<a target="_blank" rel="noopener" href="http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html%20%20%20%20%20%E2%80%9C%20Multithreading%20for%20Performance%E2%80%9D"> Multithreading for Performance</a> 提供了建议：在AsyncTask中，用弱引用来存储ImageView，通过使用弱引用来被检查ImageView是否加载完成</p>
<p>好吧，理论上是这样，我们开始行动：</p>
<ol>
<li><strong>自定义Drawable去存储异步任务重的弱引用，只有这样，才能保证task执行完毕之后，ImageView才会显示图片</strong></li>
</ol>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncDrawable</span> <span class="keyword">extends</span> <span class="title">BitmapDrawable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> WeakReference&lt;BitmapWorkerTask&gt; bitmapWorkerTaskReference;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AsyncDrawable</span><span class="params">(Resources res, Bitmap bitmap,</span></span></span><br><span class="line"><span class="function"><span class="params">            BitmapWorkerTask bitmapWorkerTask)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(res, bitmap);</span><br><span class="line">        bitmapWorkerTaskReference =</span><br><span class="line">            <span class="keyword">new</span> WeakReference&lt;BitmapWorkerTask&gt;(bitmapWorkerTask);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BitmapWorkerTask <span class="title">getBitmapWorkerTask</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> bitmapWorkerTaskReference.get();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<ol start="2">
<li> <strong>在执行BitmapWorkerTask之前，你需要创建 AsyncDrawable 并且绑定到ImageView上，通过如下代码：</strong></li>
</ol>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (cancelPotentialWork(resId, imageView)) &#123;</span><br><span class="line">        <span class="keyword">final</span> BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(imageView);</span><br><span class="line">        <span class="keyword">final</span> AsyncDrawable asyncDrawable =</span><br><span class="line">                <span class="keyword">new</span> AsyncDrawable(getResources(), mPlaceHolderBitmap, task);</span><br><span class="line">        imageView.setImageDrawable(asyncDrawable);</span><br><span class="line">        task.execute(resId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<ol start="3">
<li><p><strong>仅仅这些代码还是不够的，Google 还引入 cancelPotentialWork（）来检查是否有其他的task任务在使用当前ImageView，如果有，就会取消当前任务，取消这个做法是不是很让人眼前一亮呢！</strong></p>
<p>这是cancelPotentialWork（）的实现</p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">cancelPotentialWork</span><span class="params">(<span class="keyword">int</span> data, ImageView imageView)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (bitmapWorkerTask != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> bitmapData = bitmapWorkerTask.data;</span><br><span class="line">        <span class="comment">// If bitmapData is not yet set or it differs from the new data</span></span><br><span class="line">        <span class="keyword">if</span> (bitmapData == <span class="number">0</span> || bitmapData != data) &#123;</span><br><span class="line">            <span class="comment">// Cancel previous task</span></span><br><span class="line">            bitmapWorkerTask.cancel(<span class="keyword">true</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// The same work is already in progress</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// No task associated with the ImageView, or an existing task was cancelled</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div></li>
<li><p><strong>我们还需要get方法获得相关的ImageView</strong></p>
</li>
</ol>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> BitmapWorkerTask <span class="title">getBitmapWorkerTask</span><span class="params">(ImageView imageView)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (imageView != <span class="keyword">null</span>) &#123;</span><br><span class="line">       <span class="keyword">final</span> Drawable drawable = imageView.getDrawable();</span><br><span class="line">       <span class="keyword">if</span> (drawable <span class="keyword">instanceof</span> AsyncDrawable) &#123;</span><br><span class="line">           <span class="keyword">final</span> AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;</span><br><span class="line">           <span class="keyword">return</span> asyncDrawable.getBitmapWorkerTask();</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<ol start="5">
<li><strong>最后就是更新task中的onPostExecute（）检查任务是否取消，</strong></li>
</ol>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BitmapWorkerTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">Integer</span>, <span class="title">Void</span>, <span class="title">Bitmap</span>&gt; </span>&#123;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPostExecute</span><span class="params">(Bitmap bitmap)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isCancelled()) &#123;</span><br><span class="line">            bitmap = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (imageViewReference != <span class="keyword">null</span> &amp;&amp; bitmap != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">final</span> ImageView imageView = imageViewReference.get();</span><br><span class="line">            <span class="keyword">final</span> BitmapWorkerTask bitmapWorkerTask =</span><br><span class="line">                    getBitmapWorkerTask(imageView);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span> == bitmapWorkerTask &amp;&amp; imageView != <span class="keyword">null</span>) &#123;</span><br><span class="line">                imageView.setImageBitmap(bitmap);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>至此，我们已经了解Google 对于并发加载的解决方案，只需要在getView（）实现它们就可以啦！</p>
<h2 id="在gridview解决并发"><a href="#在GridView解决并发" class="headerlink" title="在GridView解决并发"></a>在GridView解决并发<a href="#在gridview解决并发" class="header-anchor">#</a></h2><div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageGridFragment</span> <span class="keyword">extends</span> <span class="title">Fragment</span> <span class="keyword">implements</span> <span class="title">AdapterView</span>.<span class="title">OnItemClickListener</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageAdapter</span> <span class="keyword">extends</span> <span class="title">BaseAdapter</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> View <span class="title">getView</span><span class="params">(<span class="keyword">int</span> position, View convertView, ViewGroup container)</span> </span>&#123;</span><br><span class="line">            ...</span><br><span class="line">            loadBitmap(imageResIds[position], imageView)</span><br><span class="line">            <span class="keyword">return</span> imageView;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadBitmap</span><span class="params">(<span class="keyword">int</span> resId, ImageView imageView)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (cancelPotentialWork(resId, imageView)) &#123;</span><br><span class="line">            <span class="keyword">final</span> BitmapWorkerTask task = <span class="keyword">new</span> BitmapWorkerTask(imageView);</span><br><span class="line">            <span class="keyword">final</span> AsyncDrawable asyncDrawable =</span><br><span class="line">                    <span class="keyword">new</span> AsyncDrawable(getResources(), mPlaceHolderBitmap, task);</span><br><span class="line">            imageView.setImageDrawable(asyncDrawable);</span><br><span class="line">            task.execute(resId);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncDrawable</span> <span class="keyword">extends</span> <span class="title">BitmapDrawable</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">final</span> WeakReference&lt;BitmapWorkerTask&gt; bitmapWorkerTaskReference;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">AsyncDrawable</span><span class="params">(Resources res, Bitmap bitmap,</span></span></span><br><span class="line"><span class="function"><span class="params">                BitmapWorkerTask bitmapWorkerTask)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">super</span>(res, bitmap);</span><br><span class="line">            bitmapWorkerTaskReference =</span><br><span class="line">                <span class="keyword">new</span> WeakReference&lt;BitmapWorkerTask&gt;(bitmapWorkerTask);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> BitmapWorkerTask <span class="title">getBitmapWorkerTask</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> bitmapWorkerTaskReference.get();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">cancelPotentialWork</span><span class="params">(<span class="keyword">int</span> data, ImageView imageView)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (bitmapWorkerTask != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">int</span> bitmapData = bitmapWorkerTask.data;</span><br><span class="line">            <span class="keyword">if</span> (bitmapData != data) &#123;</span><br><span class="line">                <span class="comment">// Cancel previous task</span></span><br><span class="line">                bitmapWorkerTask.cancel(<span class="keyword">true</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// The same work is already in progress</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// No task associated with the ImageView, or an existing task was cancelled</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> BitmapWorkerTask <span class="title">getBitmapWorkerTask</span><span class="params">(ImageView imageView)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (imageView != <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="keyword">final</span> Drawable drawable = imageView.getDrawable();</span><br><span class="line">           <span class="keyword">if</span> (drawable <span class="keyword">instanceof</span> AsyncDrawable) &#123;</span><br><span class="line">               <span class="keyword">final</span> AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;</span><br><span class="line">               <span class="keyword">return</span> asyncDrawable.getBitmapWorkerTask();</span><br><span class="line">           &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ... <span class="comment">// include updated BitmapWorkerTask class</span></span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>这样解决并发的办法，同理适用于ListView， Recycler<br>这也是热门加载框架ImageLoader，Volley  的加载原理。原理还是Google提出的！</p>
</blockquote>
<p>这样就可以流畅的展示图片。</p>
<h2 id="view-holder设计模式"><a href="#View-Holder设计模式" class="headerlink" title="View Holder设计模式"></a>View Holder设计模式<a href="#view-holder设计模式" class="header-anchor">#</a></h2><p>我们的代码可能会调用findViewById（），尤其是当滑动ListView，RecyclerView，GridView的时候，会使得app性能变得糟糕。甚至Adapter会返回一个已经被Android系统回收的View，可是你仍然需要初始化加载这个view并刷新它。</p>
<p>Google提出了使用 “View Holder” 设计模式</p>
<p><strong>1. 首先创建 ViewHolder类，存储子View内部所有需要展示的布局</strong></p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ViewHolder</span> </span>&#123;</span><br><span class="line">  TextView text;</span><br><span class="line">  TextView timestamp;</span><br><span class="line">  ImageView icon;</span><br><span class="line">  ProgressBar progress;</span><br><span class="line">  <span class="keyword">int</span> position;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p><strong>2.  接着填充ViewHolder并且存储到布局中</strong></p>
<div class="highlight-wrap"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="JAVA"><figure class="iseeu highlight /java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ViewHolder holder = <span class="keyword">new</span> ViewHolder();</span><br><span class="line">holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);</span><br><span class="line">holder.text = (TextView) convertView.findViewById(R.id.listitem_text);</span><br><span class="line">holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);</span><br><span class="line">holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);</span><br><span class="line">convertView.setTag(holder);</span><br></pre></td></tr></table></figure></div>
<blockquote>
<p>‘view holder’ 设计模式同样也适用于ListView，RecyclerView，GridView</p>
</blockquote>
<hr>
<h1 id="有趣的是"><a href="#有趣的是" class="headerlink" title="有趣的是"></a>有趣的是<a href="#有趣的是" class="header-anchor">#</a></h1><p>当我通宵赶完这篇博客的时候，我的计算机也提醒我内存不足了 (●’◡’●)</p>
<img src="http://cdn.yangchaofan.cn/gc9.png">



<h1 id="写本文所参考的"><a href="#写本文所参考的：" class="headerlink" title="写本文所参考的："></a>写本文所参考的：<a href="#写本文所参考的" class="header-anchor">#</a></h1><ol>
<li><a target="_blank" rel="noopener" href="http://blog.csdn.net/testcs_dn/article/details/45719357">Markdown字体颜色写法</a></li>
<li><a target="_blank" rel="noopener" href="https://classroom.udacity.com/courses/ud825/lessons">Google 官方 Android Performance 课程</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.android.com/training/building-graphics.html">Google 官方 Android  Diplaying  Bitmaps Efficiently 课程</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.android.com/training/articles/memory.html">Managing Your App’s Memory</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.android.com/training/displaying-bitmaps/process-bitmap.html#concurrency">Google 官方 Processing Bitmaps Off the UI Thread课程</a> </li>
<li><a target="_blank" rel="noopener" href="https://developer.android.com/training/displaying-bitmaps/process-bitmap.html#concurrency"> Multithreading for Performance </a></li>
</ol>
<h1 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明<a href="#说明" class="header-anchor">#</a></h1><p>后续会更新</p>
<ul>
<li> Google官方提供的ListView，RecyclerView的优化方案以及</li>
<li> Android内存管理机制</li>
<li> JVM内存管理机制</li>
</ul>
<link rel="stylesheet" href="/css/bilicard.css" type="text/css">

        

      
    </div>

      <!-- 相关文章推荐 -->
     
          

  <div class="popular-posts-header">
    <i class="fa fa-graduation-cap"></i>
    相关文章
  </div>

 <details>
   <summary>点击查看</summary>
     <ul class="popular-posts">
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\05\The-most-comprehensive-thinking-of-crash-practice-strategy\" rel="bookmark">Android Crash实践策略最全面思考</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\05\android-crash-who-kill-you\" rel="bookmark">Android Crash揭秘与实践</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\02\mtk-log\" rel="bookmark">mtk-log</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\02\android-bugfree-three-lines\" rel="bookmark">BugFree三剑客异常、日志、工具</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\02\Client-Skeleton-Screen\" rel="bookmark">Android骨架屏详解</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\01\Android-plug-in-technology-selection\" rel="bookmark">Android插件化技术选型</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\01\Android-component-Practice-Guide\" rel="bookmark">Android组件化实践指南</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2021\01\android-structure-best-practice\" rel="bookmark">Android大厂架构设计最佳实践</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2020\08\handler TOP 100 Questions\" rel="bookmark">AndroidHandler百问百答</a></div>
         
       </li>
     
       <li class="popular-posts-item">
         
         
         <div class="popular-posts-title"><a href="\blog\2018\02\MVC-MVP-MVVM -of -architecture -selection\" rel="bookmark">架构选型之MVC、MVP、MVVM</a></div>
         
       </li>
     
     </ul>
 </details>



     

    
    
    

    <div>
          
            

          
    </div>

    

    <div>
      
        <div>
    
        <div class="read-over">-------------------本文结束 <i class="fa fa-paw"></i> 感谢您的阅读-------------------</div>
    
</div>

      
    </div>

    
      <div>
        <div class="share_reward">
  <div>坚持原创技术分享，感谢您的支持和鼓励！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://cdn.yangchaofan.cn/BlogGifRes/20210313/s7mteFUqc8pH.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://cdn.yangchaofan.cn/BlogGifRes/20210313/oQnokBcx6RUO.png" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    叶金诚
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://idolcoder.gitee.io/blog/2016/06/performance-android/" title="Android性能优化【史诗巨著之内存篇】">http://idolcoder.gitee.io/blog/2016/06/performance-android/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-nd/3.0/deed.zh" rel="external nofollow" target="_blank">Creative Commons BY-NC-ND 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Android/" rel="tag"> <i class="fa fa-tag"></i> Android</a>
          
            <a href="/blog/tags/Performance/" rel="tag"> <i class="fa fa-tag"></i> Performance</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2016/06/android-communication/" rel="prev" title="详解 Android 通信">
                <i class="fa fa-chevron-left"></i> 详解 Android 通信
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2016/04/Android-TOP-100-Program/" rel="next" title="Android 百大框架排行榜">
                Android 百大框架排行榜 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "1",
        "bdMiniList": false,
        "bdPic": ""
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      },
      "slide": {
        "bdImg": "5",
        "bdPos": "left",
        "bdTop": "100"
      }
    }
  </script>

<script>
//  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
//    with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC81Mjc2OC8yOTI0NQ"></div>
    </div>

  





        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <a href="/">
              <img class="site-author-image" itemprop="image"
                src="/blog/images/head.png"
                alt="" />
              </a>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">文章</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
              <!-- 为Hexo Next主题添加哈林摇特效  -->
              <a title="收藏到书签，偶尔High一下^_^" rel="alternate" class="mw-harlem_shake_slow wobble shake" href="javascript:void(0)" onclick="javascript:(function go() {function c() {var e = document.createElement('link');e.setAttribute('type', 'text/css');e.setAttribute('rel', 'stylesheet');e.setAttribute('href', f);e.setAttribute('class', l);document.body.appendChild(e)}function h(){var e = document.getElementsByClassName(l);for(var t = 0; t< e.length; t++){document.body.removeChild(e[t])}}function p(){var e = document.createElement('div');e.setAttribute('class', a);document.body.appendChild(e);setTimeout(function(){document.body.removeChild(e)},100)}function d(e){return{height:e.offsetHeight,width:e.offsetWidth}}function v(i){var s = d(i);return s.height>e &amp;&amp;s.height<n &amp;&amp; s.width>t &amp;&amp;s.width<r}function m(e){var t=e;var n=0;while(!!t){n+=t.offsetTop;t=t.offsetParent}return n}function g(){var e=document.documentElement;if(!!window.innerWidth){return window.innerHeight}else if(e &amp;&amp; !isNaN(e.clientHeight)){return e.clientHeight}return 0}function y(){if(window.pageYOffset){return window.pageYOffset}return Math.max(document.documentElement.scrollTop,document.body.scrollTop)}function E(e){var t=m(e);return t>=w &amp;&amp; t<=b+w}var songs=['https://www.liaofuzhan.com/music/无尽光芒.mp3'];function S(){var e=document.getElementById('audio_element_id');if(e!=null){var index=parseInt(e.getAttribute('curSongIndex'));if(index>songs.length-2){index=0;}else{index++;}e.setAttribute('curSongIndex',index);N();}e.src=i;e.play()}function x(e){e.className+=' '+s+' '+o}function T(e){e.className+=' '+s+' '+u[Math.floor(Math.random()*u.length)]}function N(){var e=document.getElementsByClassName(s);var t=new RegExp('\\b'+s+'\\b');for(var n=0;n<e.length;){e[n].className=e[n].className.replace(t,'')}}function initAudioEle(){var e=document.getElementById('audio_element_id');if(e===null){e=document.createElement('audio');e.setAttribute('class',l);e.setAttribute('curSongIndex',0);e.id='audio_element_id';e.loop=false;e.bgcolor=0;e.addEventListener('canplay',function(){setTimeout(function(){x(k)},500);setTimeout(function(){N();p();for(var e=0;e<O.length;e++){T(O[e])}},15500)},true);e.addEventListener('ended',function(){N();h();go();},true);e.innerHTML='<p>If you are reading this,it is because your browser does not support the audio element. We recommend that you get a new browser.</p><p>';document.body.appendChild(e);}}initAudioEle();var e=30;var t=30;var n=350;var r=350;var curSongIndex=parseInt(document.getElementById('audio_element_id').getAttribute('curSongIndex'));var i=songs[curSongIndex];var s='mw-harlem_shake_me';var o='im_first';var u=['im_drunk','im_baked','im_trippin','im_blown'];var a='mw-strobe_light';var f='https://s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css';var l='mw_added_css';var b=g();var w=y();var C=document.getElementsByTagName('*');var k=null;for(var L=0;L<C.length;L++){var A=C[L];if(v(A)){if(E(A)){k=A;break}}}if(A===null){console.warn('Could not find a node of the right size. Please try a different page.');return}c();S();var O=[];for(var L=0;L<C.length;L++){var A=C[L];if(v(A)){O.push(A)}}})()"><i class="fa fa-music"></i> High~</a>

            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://github.com/ShaunSheep" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="mailto:zuogewoniu@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://www.douban.com/people/jincheng-ycf/" target="_blank" title="豆瓣">
                      
                        <i class="fa fa-fw fa-stack-overflow"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://www.zhihu.com/people/OscarWildeHawking" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-instagram"></i></a>
                  </span>
                
            </div>
          

            <!--
            <div id="music163player">
                <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=1336790004&auto=1&height=66"></iframe>
            </div>
            -->

          
          

          
          

          <!--近期文章版块 began-->
          
              <div class="links-of-blogroll motion-element links-of-blogroll-block">
                <div class="links-of-blogroll-title">
                  <i class="fa fa-history fa-" aria-hidden="true"></i>
                  近期文章
                </div>
                <ul class="links-of-blogroll-list">
                  
                  
                    <li class='my-links-of-blogroll-li'>
                      <a href="/blog/2021/05/The-most-comprehensive-thinking-of-crash-practice-strategy/" title="Android Crash实践策略最全面思考" target="_blank">Android Crash实践策略最全面思考</a>
                    </li>
                  
                    <li class='my-links-of-blogroll-li'>
                      <a href="/blog/2021/05/android-crash-who-kill-you/" title="Android Crash揭秘与实践" target="_blank">Android Crash揭秘与实践</a>
                    </li>
                  
                    <li class='my-links-of-blogroll-li'>
                      <a href="/blog/2021/04/Career-stability-experience/" title="职业稳定性杂谈" target="_blank">职业稳定性杂谈</a>
                    </li>
                  
                    <li class='my-links-of-blogroll-li'>
                      <a href="/blog/2021/02/mtk-log/" title="mtk-log" target="_blank">mtk-log</a>
                    </li>
                  
                    <li class='my-links-of-blogroll-li'>
                      <a href="/blog/2021/02/android-bugfree-three-lines/" title="BugFree三剑客异常、日志、工具" target="_blank">BugFree三剑客异常、日志、工具</a>
                    </li>
                  
                </ul>
              </div>
          
          <!--近期文章版块 end-->

          
              <!-- canvas粒子时钟 -->
              <!-- canvas粒子时钟 https://www.cnblogs.com/xiaohuochai/p/6368039.html
  https://www.html5tricks.com/html5-canvas-dance-time.html
 -->
<div id="">
  <canvas id="canvas" style="width:60%;">
</div>
<script async>
(function(){
  var WINDOW_WIDTH = 820;
  		var WINDOW_HEIGHT = 250;
  		var RADIUS = 7; //球半径
  		var NUMBER_GAP = 10; //数字之间的间隙
  		var u=0.65; //碰撞能量损耗系数
  		var context; //Canvas绘制上下文
  		var balls = []; //存储彩色的小球
  		const colors = ["#33B5E5","#0099CC","#AA66CC","#9933CC","#99CC00","#669900","#FFBB33","#FF8800","#FF4444","#CC0000"]; //彩色小球的颜色
  		var currentNums = []; //屏幕显示的8个字符
  		var digit =
                  [
                      [
                          [0,0,1,1,1,0,0],
                          [0,1,1,0,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,0,1,1,0],
                          [0,0,1,1,1,0,0]
                      ],//0
                      [
                          [0,0,0,1,1,0,0],
                          [0,1,1,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [1,1,1,1,1,1,1]
                      ],//1
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,0,0,0],
                          [0,1,1,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,0,0,0,1,1],
                          [1,1,1,1,1,1,1]
                      ],//2
                      [
                          [1,1,1,1,1,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,1,0,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//3
                      [
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,1,0],
                          [0,0,1,1,1,1,0],
                          [0,1,1,0,1,1,0],
                          [1,1,0,0,1,1,0],
                          [1,1,1,1,1,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,1,1]
                      ],//4
                      [
                          [1,1,1,1,1,1,1],
                          [1,1,0,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,1,1,1,1,0],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//5
                      [
                          [0,0,0,0,1,1,0],
                          [0,0,1,1,0,0,0],
                          [0,1,1,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,0,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//6
                      [
                          [1,1,1,1,1,1,1],
                          [1,1,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0]
                      ],//7
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//8
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,1,1,0,0,0,0]
                      ],//9
                      [
                          [0,0,0,0],
                          [0,0,0,0],
                          [0,1,1,0],
                          [0,1,1,0],
                          [0,0,0,0],
                          [0,0,0,0],
                          [0,1,1,0],
                          [0,1,1,0],
                          [0,0,0,0],
                          [0,0,0,0]
                      ]//:
                  ];

  		function drawDatetime(cxt){
  			var nums = [];

  			context.fillStyle="#005eac"
  			var date = new Date();
  			var offsetX = 70, offsetY = 30;
  			var hours = date.getHours();
  			var num1 = Math.floor(hours/10);
  			var num2 = hours%10;
  			nums.push({num: num1});
  			nums.push({num: num2});
  			nums.push({num: 10}); //冒号
  			var minutes = date.getMinutes();
  			var num1 = Math.floor(minutes/10);
  			var num2 = minutes%10;
  			nums.push({num: num1});
  			nums.push({num: num2});
  			nums.push({num: 10}); //冒号
  			var seconds = date.getSeconds();
  			var num1 = Math.floor(seconds/10);
  			var num2 = seconds%10;
  			nums.push({num: num1});
  			nums.push({num: num2});

  			for(var x = 0;x<nums.length;x++){
  				nums[x].offsetX = offsetX;
  				offsetX = drawSingleNumber(offsetX,offsetY, nums[x].num,cxt);
  				//两个数字连一块，应该间隔一些距离
  				if(x<nums.length-1){
  					if((nums[x].num!=10) &&(nums[x+1].num!=10)){
  						offsetX+=NUMBER_GAP;
  					}
  				}
  			}

  			//说明这是初始化
  			if(currentNums.length ==0){
  				currentNums = nums;
  			}else{
  				//进行比较
  				for(var index = 0;index<currentNums.length;index++){
  					if(currentNums[index].num!=nums[index].num){
  						//不一样时，添加彩色小球
  						addBalls(nums[index]);
  						currentNums[index].num=nums[index].num;
  					}
  				}
  			}
  			renderBalls(cxt);
  			updateBalls();

  			return date;
  		}

  		function addBalls (item) {
  			var num = item.num;
  			var numMatrix = digit[num];
  			for(var y = 0;y<numMatrix.length;y++){
  				for(var x = 0;x<numMatrix[y].length;x++){
  					if(numMatrix[y][x]==1){
  						var ball={
  							offsetX:item.offsetX+RADIUS+RADIUS*2*x,
  							offsetY:30+RADIUS+RADIUS*2*y,
  							color:colors[Math.floor(Math.random()*colors.length)],
  							g:1.5+Math.random(),
  							vx:Math.pow(-1, Math.ceil(Math.random()*10))*4+Math.random(),
  							vy:-5
  						}
  						balls.push(ball);
  					}
  				}
  			}
  		}

  		function renderBalls(cxt){
  			for(var index = 0;index<balls.length;index++){
  				cxt.beginPath();
  				cxt.fillStyle=balls[index].color;
  				cxt.arc(balls[index].offsetX, balls[index].offsetY, RADIUS, 0, 2*Math.PI);
  				cxt.fill();
  			}
  		}

  		function updateBalls () {
  			var i =0;
  			for(var index = 0;index<balls.length;index++){
  				var ball = balls[index];
  				ball.offsetX += ball.vx;
  				ball.offsetY += ball.vy;
  				ball.vy+=ball.g;
  				if(ball.offsetY > (WINDOW_HEIGHT-RADIUS)){
  					ball.offsetY= WINDOW_HEIGHT-RADIUS;
  					ball.vy=-ball.vy*u;
  				}
  				if(ball.offsetX>RADIUS&&ball.offsetX<(WINDOW_WIDTH-RADIUS)){

  					balls[i]=balls[index];
  					i++;
  				}
  			}
  			//去除出边界的球
  			for(;i<balls.length;i++){
  				balls.pop();
  			}
  		}
  		function drawSingleNumber(offsetX, offsetY, num, cxt){
  			var numMatrix = digit[num];
  			for(var y = 0;y<numMatrix.length;y++){
  				for(var x = 0;x<numMatrix[y].length;x++){
  					if(numMatrix[y][x]==1){
  						cxt.beginPath();
  						cxt.arc(offsetX+RADIUS+RADIUS*2*x,offsetY+RADIUS+RADIUS*2*y,RADIUS,0,2*Math.PI);
  						cxt.fill();
  					}
  				}
  			}
  			cxt.beginPath();
  			offsetX += numMatrix[0].length*RADIUS*2;
  			return offsetX;
  		}

  		var canvas = document.getElementById("canvas");
  		canvas.width=WINDOW_WIDTH;
  		canvas.height=WINDOW_HEIGHT;
  		context = canvas.getContext("2d");

  		//记录当前绘制的时刻
  		var currentDate = new Date();

  		setInterval(function(){
  			//清空整个Canvas，重新绘制内容
  			context.clearRect(0, 0, context.canvas.width, context.canvas.height);
  			drawDatetime(context);
  		}, 50)
})();
</script>

          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%85%B3%E6%B3%A8%E6%80%A7%E8%83%BD"><span class="nav-number">1.</span> <span class="nav-text">为什么关注性能</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BC%98%E5%8C%96app%E7%9A%84%E6%80%A7%E8%83%BD"><span class="nav-number">2.</span> <span class="nav-text">如何优化app的性能？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%85%B3%E6%B3%A8%E5%86%85%E5%AD%98"><span class="nav-number">3.</span> <span class="nav-text">为什么关注内存</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#java%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6%E5%AE%98%E6%96%B9%E8%AF%A6%E8%A7%A3"><span class="nav-number">4.</span> <span class="nav-text">Java垃圾回收机制官方详解</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#memory-monitor"><span class="nav-number">5.</span> <span class="nav-text">Memory Monitor</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="nav-number">6.</span> <span class="nav-text">内存泄漏</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#heap-viewer"><span class="nav-number">7.</span> <span class="nav-text">Heap Viewer</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%AB%98%E6%95%88%E5%8A%A0%E8%BD%BD%E5%9B%BE%E7%89%87%E5%9B%BE%E7%89%87"><span class="nav-number">8.</span> <span class="nav-text">高效加载图片图片</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8F%AA%E5%85%B3%E6%B3%A8%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E8%80%8C%E4%B8%8D%E5%8E%BB%E5%A4%84%E7%90%86%E5%85%B6%E4%BB%96%E6%95%B0%E6%8D%AE%E6%9D%A5%E8%A7%A3%E5%86%B3%E5%86%85%E5%AD%98%E4%B8%8D%E8%B6%B3%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-number">8.1.</span> <span class="nav-text">为什么只关注图片加载，而不去处理其他数据来解决内存不足的问题？</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%AB%98%E6%95%88%E7%9A%84%E5%8A%A0%E8%BD%BD%E5%A4%A7%E5%9B%BE"><span class="nav-number">9.</span> <span class="nav-text">高效的加载大图：</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%AA%E9%9C%80%E4%B8%89%E6%AD%A5"><span class="nav-number">9.1.</span> <span class="nav-text">只需三步</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%AF%BB%E5%8F%96%E5%86%85%E5%AD%98%E4%B8%ADbitmap%E7%9A%84%E5%B0%BA%E5%AF%B8%E5%92%8C%E7%B1%BB%E5%9E%8B"><span class="nav-number">9.2.</span> <span class="nav-text">1. 读取内存中Bitmap的尺寸和类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8A%A0%E8%BD%BD%E4%B8%80%E5%BC%A0%E5%B0%8F%E5%9B%BE%E4%BD%BF%E5%BE%97%E7%B3%BB%E7%BB%9F%E5%88%86%E9%85%8D%E8%BE%83%E5%B0%91%E7%9A%84%E5%86%85%E5%AD%98%E7%BB%99%E5%AE%83"><span class="nav-number">9.3.</span> <span class="nav-text">2. 加载一张小图，使得系统分配较少的内存给它。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E6%8E%A5%E7%9D%80%E4%B8%BA%E6%88%91%E4%BB%AC%E7%9A%84ui%E7%BB%84%E4%BB%B6imageview%E8%AE%BE%E7%BD%AE%E4%B8%80%E5%BC%A0%E7%BC%A9%E7%95%A5%E5%9B%BE%E5%92%AF"><span class="nav-number">9.4.</span> <span class="nav-text">3.接着为我们的UI组件ImageView设置一张缩略图咯：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BFasynctask%E5%8A%A0%E8%BD%BDbitmap"><span class="nav-number">10.</span> <span class="nav-text">使AsyncTask加载Bitmap</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8lrucache%E7%BC%93%E5%AD%98%E5%9B%BE%E7%89%87"><span class="nav-number">11.</span> <span class="nav-text">使用Lrucache缓存图片</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A1%A5%E5%85%85-ui%E7%BB%84%E4%BB%B6%E5%B9%B6%E5%8F%91%E6%80%A7%E9%97%AE%E9%A2%98"><span class="nav-number">12.</span> <span class="nav-text">补充-UI组件并发性问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#viewpager"><span class="nav-number">13.</span> <span class="nav-text">ViewPager</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%9C%8B%E4%B8%8A%E5%8E%BB%E5%B7%B2%E7%BB%8F%E5%A4%A7%E5%8A%9F%E5%91%8A%E6%88%90-%E4%BA%86%E4%BD%86%E4%BA%8B%E5%AE%9E%E7%9C%9F%E7%9A%84%E5%A6%82%E6%AD%A4%E5%90%97"><span class="nav-number">13.1.</span> <span class="nav-text">看上去已经大功告成 了，但事实真的如此吗？</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#recyclerviewgridviewlistview"><span class="nav-number">14.</span> <span class="nav-text">RecyclerView，GridView，ListView</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B6%E5%8F%91%E9%97%AE%E9%A2%98"><span class="nav-number">14.1.</span> <span class="nav-text">并发问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9C%A8gridview%E8%A7%A3%E5%86%B3%E5%B9%B6%E5%8F%91"><span class="nav-number">14.2.</span> <span class="nav-text">在GridView解决并发</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#view-holder%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-number">14.3.</span> <span class="nav-text">View Holder设计模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9C%89%E8%B6%A3%E7%9A%84%E6%98%AF"><span class="nav-number">15.</span> <span class="nav-text">有趣的是</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%86%99%E6%9C%AC%E6%96%87%E6%89%80%E5%8F%82%E8%80%83%E7%9A%84"><span class="nav-number">16.</span> <span class="nav-text">写本文所参考的：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%AF%B4%E6%98%8E"><span class="nav-number">17.</span> <span class="nav-text">说明</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

      

      <!-- 标签云 -->
      <!--
      
      <script type="text/javascript" charset="utf-8" src="/js/tagcloud.js"></script>
      <script type="text/javascript" charset="utf-8" src="/js/tagcanvas.js"></script>
      <div class="widget-wrap">
      <h3 class="widget-title">Tag Cloud</h3>
      <div id="myCanvasContainer" class="widget tagcloud">
          <canvas width="250" height="250" id="resCanvas" style="width=100%">
              <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Android/" rel="tag">Android</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/AndroidUI%E4%BC%98%E5%8C%96/" rel="tag">AndroidUI优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Android%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">Android性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/BugFree/" rel="tag">BugFree</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Communication/" rel="tag">Communication</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Handler/" rel="tag">Handler</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Performance/" rel="tag">Performance</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E4%B8%AA%E4%BA%BA%E6%95%99%E8%82%B2/" rel="tag">个人教育</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95/" rel="tag">学习方法</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%BC%80%E6%BA%90%E6%A1%86%E6%9E%B6/" rel="tag">开源框架</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E6%8A%80%E6%9C%AF%E9%80%89%E5%9E%8B/" rel="tag">技术选型</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E6%9D%82%E8%B0%88/" rel="tag">杂谈</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E7%A8%8B%E5%BA%8F%E4%BA%BA%E7%94%9F%EF%BC%8C%E6%9D%82%E8%B0%88/" rel="tag">程序人生，杂谈</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a><span class="tag-list-count">1</span></li></ul>
          </canvas>
      </div>
      </div>
      
      -->
      <!-- 标签云 -->

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
       <i class="fa fa-heartbeat"></i>
  </span>
  <!--
    <span class="author" itemprop="copyrightHolder"> &nbsp;叶金诚</span>
  -->
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">111k</span>
  
</div>














  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize("");
    }
  </script>



        
<div class="busuanzi-count">
  <!--
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  -->
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

   

  
  
    
      <span class="site-uv">
        
        我的第 <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 位朋友，
      </span>
    

    
      <span class="site-pv">
        历经 <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次回眸才与你相遇
        <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      </span>
    
  

</div>








        
      </div>
    </footer>

    
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  










  



  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/velocity-animate@1.2.1/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/velocity-animate@1.2.1/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script id="ribbon" type="text/javascript" size="60" alpha="0.1"  zIndex="-1" src="/blog/lib/canvas-ribbon/canvas-ribbon.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  















  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





    <script>  function addCount(Counter){var $visitors=$('.leancloud_visitors');var url=$visitors.attr('id').trim();var title=$visitors.attr('data-flag-title').trim();Counter('get','/classes/Counter',{where:JSON.stringify({url})}).done(function({results}){if(results.length>0){var counter=results[0]; var $element=$(document.getElementById(url));$element.find('.leancloud-visitors-count').text(counter.time+1);Counter('put','/classes/Counter/'+counter.objectId,JSON.stringify({time:{'__op':'Increment','amount':1}})) .fail(function({responseJSON}){console.log('Failed to save Visitor num, with error message: '+responseJSON.error);})}else{ Counter('post','/classes/Counter',JSON.stringify({title:title,url:url,time:1})).done(function(){var $element=$(document.getElementById(url));$element.find('.leancloud-visitors-count').text(1);}).fail(function(){console.log('Failed to create');});}}).fail(function({responseJSON}){console.log('LeanCloud Counter Error: '+responseJSON.code+' '+responseJSON.error);});}$(function(){$.get('https://app-router.leancloud.cn/2/route?appId='+'MFn6psRe8xtnq9sq6lv9MJks-gzGzoHsz').done(function({api_server}){var Counter=function(method,url,data){return $.ajax({method:method,url:'https://'+api_server+'/1.1'+url,headers:{'X-LC-Id':'MFn6psRe8xtnq9sq6lv9MJks-gzGzoHsz','X-LC-Key':'pi8Pa2aH3XpcaovMyqIXVuOP','Content-Type':'application/json',},data:data});};  const localhost=/http:\/\/(localhost|127.0.0.1|0.0.0.0)/;if(localhost.test(document.URL))return;addCount(Counter);});});</script>

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/blog/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/blog/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  


  

  


  <!-- Tidio 在线联系功能、鼠标点击特效、页面反馈...-->
  <script type="text/javascript" src="/js/src/clipboard.min.js"></script>
<script type="text/javascript" src="/js/src/clipboard-use.js"></script>



  
    <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas>
    <script async src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
    <script async src="/js/cursor/explosion.min.js"></script>
  










  <script src="/js/src/activate-power-mode.min.js"></script>
  <script>
    POWERMODE.colorful = true;
    POWERMODE.shake = false;
    document.body.addEventListener('input', POWERMODE);
  </script>






  <script async language="javascript">

    var div = document.createElement("div");
    //插入到自定义的theme-info或者copyright之后
    var copyright = document.querySelector(".theme-info2") || document.querySelector(".copyright");

    function show_run_time(){
        window.setTimeout("show_run_time()", 1000);
      // BirthDay=new Date("08/07/2019 20:00:00");
        BirthDay=new Date("08/07/2016 20:00:00");
        today=new Date();
        timeold=(today.getTime()-BirthDay.getTime());
        sectimeold=timeold/1000
        secondsold=Math.floor(sectimeold);
        msPerDay=24*60*60*1000
        e_daysold=timeold/msPerDay
        daysold=Math.floor(e_daysold);
        e_hrsold=(e_daysold-daysold)*24;
        hrsold=setzero(Math.floor(e_hrsold));
        e_minsold=(e_hrsold-hrsold)*60;
        minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
        seconds=setzero(Math.floor((e_minsold-minsold)*60));

        // 使用zh-Hans.yml的文字替换
        div.innerHTML = "我已在此等候你 " + "<span style='color: #1890ff'> " + daysold + " </span> 天 <span style='color: #1890ff'>" + hrsold + " </span>时 <span style='color: #1890ff'>" + minsold + " </span>分 <span style='color: #1890ff'>" + seconds + " </span>秒 ";

        document.querySelector(".footer-inner").insertBefore(div, copyright.nextSibling);

    }
    function setzero(i){
        if (i<10)
        {i="0" + i};
        return i;
    }

    show_run_time();

  </script>




<!-- 旋转魔方 -->

   
      
<style>
  /*最外层容器样式*/
  .wrap {
    width: 0px;
    height: 0px;
    /*margin: 80px;*/
    /*position: relative;*/
	     /*显示位置*/
    position: fixed;
    bottom: 120px;
    right: 240px;
    z-index: 999;
  }

  /*包裹所有容器样式*/
  .cube {
    width: 0px;
    height: 0px;
    margin: 0 auto;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    transform: rotateX(-30deg) rotateY(-80deg);
    animation: rotate linear 10s infinite;
  }

  @-webkit-keyframes rotate {
    from {
      transform: rotateX(0deg) rotateY(0deg);
    }
    to {
      transform: rotateX(360deg) rotateY(360deg);
    }
  }

  .cube div {
    position: absolute;
    width: 50px;
    height: 50px;
    opacity: 0.8;
    transition: all .4s;
  }

  /*定义所有图片样式*/
  .pic {
    width: 50px;
    height: 50px;
  }

  .cube .out_front {
    transform: rotateY(0deg) translateZ(25px);
  }

  .cube .out_back {
    transform: translateZ(-25px) rotateY(180deg);
  }

  .cube .out_left {
    transform: rotateY(-90deg) translateZ(25px);
  }

  .cube .out_right {
    transform: rotateY(90deg) translateZ(25px);
  }

  .cube .out_top {
    transform: rotateX(90deg) translateZ(25px);
  }

  .cube .out_bottom {
    transform: rotateX(-90deg) translateZ(25px);
  }

  /*定义小正方体样式*/
  .cube span {
    display: block;
    width: 25px;
    height: 25px;
    position: absolute;
    top: 12px;
    left: 12px;
  }

  .cube .in_pic {
    width: 25px;
    height:25px;
  }

  .cube .in_front {
    transform: rotateY(0deg) translateZ(12px);
  }

  .cube .in_back {
    transform: translateZ(-12px) rotateY(180deg);
  }

  .cube .in_left {
    transform: rotateY(-90deg) translateZ(12px);
  }

  .cube .in_right {
    transform: rotateY(90deg) translateZ(12px);
  }

  .cube .in_top {
    transform: rotateX(90deg) translateZ(12px);
  }

  .cube .in_bottom {
    transform: rotateX(-90deg) translateZ(12px);
  }

  /*鼠标移入后样式*/
  .cube:hover .out_front {
    transform: rotateY(0deg) translateZ(50px);
  }

  .cube:hover .out_back {
    transform: translateZ(-50px) rotateY(180deg);
  }

  .cube:hover .out_left {
    transform: rotateY(-90deg) translateZ(50px);
  }

  .cube:hover .out_right {
    transform: rotateY(90deg) translateZ(50px);
  }

  .cube:hover .out_top {
    transform: rotateX(90deg) translateZ(50px);
  }

  .cube:hover .out_bottom {
    transform: rotateX(-90deg) translateZ(50px);
  }
</style>

<div class="wrap">

		<!--包裹所有元素的容器-->
		<div class="cube">
			<!--前面图片 -->
			<div class="out_front">
			  <a onclick="back2top()">
				  <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
				</a>
			</div>
			<!--后面图片 -->
			<div class="out_back">
				<a onclick="back2top()">
          <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
        </a>
			</div>
			<!--左面图片 -->
			<div class="out_left">
        <a onclick="back2top()">
				  <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
				</a>
			</div>
			<!--右面图片 -->
			<div class="out_right">
				<a onclick="back2top()">
          <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
        </a>
			</div>
			<!--上面图片 -->
			<div class="out_top">
				<a onclick="back2top()">
          <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
        </a>
			</div>
			<!--下面图片 -->
			<div class="out_bottom">
				<a onclick="back2top()">
          <img src="http://cdn.yangchaofan.cn/BlogGifRes/20210307/lAq9mKTioPeO.png" class="pic" />
        </a>
			</div>

			<!--小正方体 -->
			<span class="in_front">
				<img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
			<span class="in_back">
			     <img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
			<span class="in_left">
				<img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
			<span class="in_right">
				<img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
			<span class="in_top">
				<img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
			<span class="in_bottom">
				<img src="https://s2.ax1x.com/2019/10/14/KptCPf.th.jpg" class="in_pic" />
			</span>
		</div>

</div>

<script>
  function back2top(){
    $('html, body').animate({scrollTop: 0}, 500);
  }
</script>

   


<!-- Console 输出第三方个性化字体 -->

  <script async type="text/javascript" src="/blog/figlet/fetch.min.js"></script>
  <script type="text/javascript" src="/blog/figlet/figlet.js"></script>
  <script type="text/javascript">

      figlet.defaults({fontPath: "/figlet/fonts"});
      figlet("Welcome To Leaface", "Big Money-ne", function(err, text) {
          if (err) {
              console.log("something went wrong...");
              console.dir(err);
              return;
          }
          console.log(text);
      });
  </script>


  <!-- Console 输出自定义字体 -->
  
    <script async type="text/javascript">
        var text = "Welcome To Leaface";
        var date = '2021-06-10';
        console.log("%c " + text, "font-size:100px;color:white;border-radius:20px;height:200px; background:-webkit-linear-gradient(yellow,orange,red,green,blue,purple);text-shadow: 0 1px 0 #ccc,0 2px 0 #c9c9c9,0 3px 0 #bbb,0 4px 0 #b9b9b9,0 5px 0 #aaa,0 6px 1px rgba(0,0,0,.1),0 0 5px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.3),0 3px 5px rgba(0,0,0,.2),0 5px 10px rgba(0,0,0,.25),0 10px 10px rgba(0,0,0,.2),0 20px 20px rgba(0,0,0,.15);");
        console.info('\n' + ' %c Leafae Site %c https://www.liaofuzhan.com ' + '\n', 'color: #fadfa3; background: #030307; padding:5px 0;', 'background: #fadfa3; padding:5px 0;');
        console.info('\n' + ' %c Leafae QQ %c 793458585 ' + '\n', 'color: #fadfa3; background: #030307; padding:5px 0;', 'background: #fadfa3; padding:5px 0;');
        console.info('\n' + ' %c Leafae Wechat %c leaface ' + '\n', 'color: #fadfa3; background: #030307; padding:5px 0;', 'background: #fadfa3; padding:5px 0;');
       // console.log("%c Time: " + date, "font-size:100px;white:"+fcolor+";border-radius:20px;height:200px; background:-webkit-linear-gradient(yellow,orange,red,green,blue,purple);text-shadow: 0 1px 0 #ccc,0 2px 0 #c9c9c9,0 3px 0 #bbb,0 4px 0 #b9b9b9,0 5px 0 #aaa,0 6px 1px rgba(0,0,0,.1),0 0 5px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.3),0 3px 5px rgba(0,0,0,.2),0 5px 10px rgba(0,0,0,.25),0 10px 10px rgba(0,0,0,.2),0 20px 20px rgba(0,0,0,.15);  background-image: linear-gradient(to right, orangered, orange, gold, lightgreen, cyan, dodgerblue, mediumpurple, hotpink, orangered);");
       // console.log("%c .", "padding:300px 600px;line-height:10px;background:url(https://s2.ax1x.com/2019/10/17/KkoAJJ.md.png) no-repeat;");
    </script>
  


  <!-- 看板娘 -->
  
      <script async src="/live2d-widget/autoload.js"></script>
  
	<!-- leafacePlayer -->
	
	<script id="lfz" src="http://player.liaofuzhan.com/player/player.js" key=1368557075310858241></script>
	

  

  

  <!-- 代码块复制功能 -->
  <script async type="text/javascript" src="/js/src/clipboard.min.js"></script>
  <script async type="text/javascript" src="/js/src/clipboard-use.js"></script>
 

  <!--share.js-->
  <link async rel="stylesheet" href="/sharejs/css/share.min.css">
  <script async src="/sharejs/js/social-share.min.js"></script>

  <!-- 模仿知乎卡片样式链接、崩溃欺骗特效 -->
  <script async type="text/javascript" src="/js/src/linkcard.js"></script>

  <!--崩溃欺骗 放在js文件最后-->
  <!--
  <script type="text/javascript" src="/js/src/crash_cheat.js"></script>
  -->

 

<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
